package cn.clementine.core.svc;

import cn.clementine.core.pojo.DatabaseCreateInfo;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Service
public class DatabaseService {
    public List<Map<String, Object>> executeQuery(String url, String username, String password, String sql) {
        DataSource dataSource = createDataSource(url, username, password);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate.queryForList(sql);
    }

    public String createDatabase(String url, String username, String password, DatabaseCreateInfo info) {
        DataSource dataSource = createDataSource(url, username, password);
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("dbName", info.getDbName());
        parameters.addValue("charset", info.getCharset());
        parameters.addValue("dbUsername", info.getDbUsername());
        parameters.addValue("dbPassword", info.getDbPassword());
        parameters.addValue("privileges", info.getPrivileges());

        try {
            jdbcTemplate.update("CREATE DATABASE :dbName CHARACTER SET :charset", parameters);
            jdbcTemplate.update("CREATE USER ':dbUsername'@'localhost' IDENTIFIED BY ':dbPassword'", parameters);
            jdbcTemplate.update("GRANT :privileges ON :dbName.* TO ':dbUsername'@'localhost'", parameters);
            jdbcTemplate.update("FLUSH PRIVILEGES", parameters);
            return "Database creation successful!";
        } catch (DataAccessException e) {
            // handle the error here, you might want to rethrow it or return a specific message
            return "Database creation failed: " + e.getMessage();
        }
    }
    private DataSource createDataSource(String url, String username, String password) {
        com.zaxxer.hikari.HikariDataSource ds = new com.zaxxer.hikari.HikariDataSource();
        ds.setJdbcUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);

        return ds;
    }
}